package com.qf.service.Impl;

import com.qf.common.AliyunOSSConstants;
import com.qf.controller.UserController;
import com.qf.entity.UserDTO;
import com.qf.entity.UserExcel;
import com.qf.mapper.UserMapper;
import com.qf.service.UserService;
import com.qf.util.JwtUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.qf.entity.User;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.plaf.UIResource;
import java.util.*;

/**
 * --- 包的 ---
 *
 * @author ding
 * @date 2025/4/27
 * @desc
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired// 因为SecurityConfig中已经配置了AuthenticationManager，所以这里可以直接注入
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;


    @Autowired
    private UserMapper mapper;

    @Override
    public User login(User user) {
        // // 用户验证
        // Authentication authentication = null;
        // try {
        //     // 该方法会去调用MyUserDetailsService.loadUserByUsername
        //     authentication = authenticationManager
        //             .authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
        // } catch (Exception e) {
        //     if (e instanceof BadCredentialsException) {
        //         throw new RuntimeException("用户认证失败");
        //     } else {
        //         throw new RuntimeException(e.getMessage());
        //     }
        // }
        //
        // // 认证成功，生成token
        // // 生成jwt
        // Map<String, Object> claims = new HashMap<>();
        // claims.put("username", authentication.getName());
        // // 获取权限对象，用于提取权限数据
        // Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        // Set<String> authoritySet = new HashSet<>();
        // authorities.forEach(item -> authoritySet.add(item.getAuthority()));
        // // 将权限数据放入claims,用于存入jwt
        // claims.put("perms", authoritySet);
        // return jwtUtils.createJwt(claims);
        return mapper.login(user);
    }

    private Logger logger = LogManager.getLogger(UserController.class);

    @Override
    public List<User> findAll() {
        return mapper.findAll();
    }

    @Override
    public boolean update(User user) {
        // 1. 获取用户头像路径
        String filePath = user.getAvatar();
        // 2. 调用阿里云OSS工具类删除原来的头像
        if (filePath != null && !filePath.isEmpty()) {
            String avatarPath = filePath.substring(AliyunOSSConstants.PUBLIC_URL.length());
            user.setAvatar(avatarPath);
        }
        return mapper.update(user);
    }

    @Override
    public List<User> findAll2(UserDTO userDTO) {
        return mapper.findAll2(userDTO);
    }

    @Override
    public boolean deleteById(int id) {
        return mapper.deleteById(id);
    }

    @Override
    public boolean batchDelete(List<Integer> ids) {
        return mapper.batchDelete(ids);
    }

    @Override
    public boolean add(User user) {
         return mapper.add(user);
    }

    /**
     * 用户注册
     *
     * @param sysUser 用户对象
     * return void
     */
    @Override
    public void save(User sysUser) {
        // 应该对密码进行加密处理
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder( );
        String pwd = passwordEncoder.encode(sysUser.getPassword( ));
        sysUser.setPassword(pwd);

        // 插入数据库
        mapper.save(sysUser);
    }

    /**
     * 用户登录--实现了权限认证
     *
     * @param username 用户名
     * @param password 密码
     * return String
     */
    @Override
    public String loginByUsernameAndPassword(String username, String password) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用MyUserDetailsService.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new RuntimeException("用户认证失败");
            } else {
                throw new RuntimeException(e.getMessage());
            }
        }

        // 认证成功，生成token
        // 生成jwt
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", authentication.getName());
        // 获取权限对象，用于提取权限数据
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        Set<String> authoritySet = new HashSet<>();
        authorities.forEach(item -> authoritySet.add(item.getAuthority()));
        // 将权限数据放入claims,用于存入jwt
        claims.put("perms", authoritySet);
        return jwtUtils.createJwt(claims);
    }

    /**
     * 根据用户名获取用户信息
     *
     * @param username 用户名
     * return User
     */
    @Override
    public User getUserByUsername(String username) {
        return mapper.getUserByUserName(username);
    }

    @Override
    public void insertBatch(List<UserExcel> cachedDataList) {
        mapper.insertBatch(cachedDataList);
    }

    @Override
    public String login2(User user) {
        // 用户验证
        Authentication authentication = null;
        try {  // 到这里了
            // 该方法会去调用MyUserDetailsService.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                System.out.println("e = " + e);
                throw new RuntimeException("用户认证失败");
            } else {
                throw new RuntimeException(e.getMessage());
            }
        }

        // 用户验证
        // Authentication authentication = null;
        // try {
        //     // 使用UsernamePasswordAuthenticationToken进行认证
        //     authentication = authenticationManager.authenticate(
        //             new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword())
        //     );
        // } catch (BadCredentialsException e) {
        //     logger.error("密码错误: " + e.getMessage());
        //     throw new RuntimeException("密码错误");
        // } catch (UsernameNotFoundException e) {
        //     logger.error("用户名未找到: " + e.getMessage());
        //     throw new RuntimeException("用户名未找到");
        // } catch (Exception e) {
        //     logger.error("认证过程中发生异常: " + e.getMessage());
        //     throw new RuntimeException(e.getMessage());
        // }

        // 认证成功，生成token
        // 生成jwt
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", authentication.getName());
        // 获取权限对象，用于提取权限数据
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        Set<String> authoritySet = new HashSet<>();
        authorities.forEach(item -> authoritySet.add(item.getAuthority()));
        // 将权限数据放入claims,用于存入jwt
        claims.put("perms", authoritySet);
        return jwtUtils.createJwt(claims);
    }
}
